﻿using CIS.DB;
using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using System;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Threading.Tasks;
using System.Web.Mvc;
using static System.Net.Mime.MediaTypeNames;

namespace CIS.Web.Controllers
{
	[RoutePrefix("ConferenceNewsList")]
	public class ConferenceNewsListController : BaseDbController
	{
		[Route("Index/{ConferenceId}")]
		public async Task<ActionResult> Index(string conferenceId)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", conferenceId);

			var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.Status == ConstValues.Status.正常 &&
						x.ID == conferenceId);

			ViewBag.ConferenceId = conferenceId;
			ViewBag.ConferenceName = conferenceMaster.ConferenceName;
			ViewBag.ControllerName = Resources.ConferenceNewsList;
			ViewBag.Language = conferenceMaster.IsInternational ? ConstValues.Language.En : ConstValues.Language.Cn;

			var model = new ConferenceNewsListModel();
			model.ConferenceId = conferenceId;
			LoginUser.ConferenceFunctionIdList = Utility.GetConferenceFunctionIdList(conferenceId);
			return View(model);
		}

		public async Task<JsonCamelCaseResult> GetData(int? page, int? rows, string sort, string order, ConferenceNewsListModel model)
		{
			int take = rows ?? ConstValues.DefaultGridRows;
			int skip = ((page ?? 1) - 1) * take;

			var sql = DbContext.NewsListInfo.AsNoTracking().Where(x => !string.IsNullOrEmpty(x.Status) && x.ConferenceId == model.ConferenceId);
			if (!string.IsNullOrWhiteSpace(model.SelNewsListName) && model.SelNewsListName != "")
			{
				sql = sql.Where(x => x.NewsListName.Contains(model.SelNewsListName));
			}
			int total = await sql.CountAsync();

			if (!string.IsNullOrEmpty(sort))
			{
				sql = sql.OrderBy(sort + ConstValues.chrSpace + order).Skip(skip).Take(take);
			}
			else
			{
				sql = sql.OrderBy(x => x.Sort).ThenByDescending(x => x.UpdateDate).ThenBy(x => x.NewsListName).Skip(skip).Take(take);
			}

			var sqlResult = await sql.ToListAsync();

			var result = sqlResult.Select(x => new
			{
				ID = x.ID,
				NewsListName = x.NewsListName,
				NewsListPic = x.NewsListPic,
				NewsListPosition = x.NewsListPosition,
				NewsStyle = x.NewsStyle,
				Link = x.Link,
				Status = x.Status,
				Sort = x.Sort,
				Remark = x.Remark,
				Creator = x.Creator,
				CreateIP = x.CreateIP,
				CreateDate = Request.Cookies["_culture"].Value == ConstValues.Language.Cn ?
					x.CreateDate.Value.ToString("yyyy-MM-dd") :
					x.CreateDate.Value.ToString("MM/dd/yyyy")
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result,
			},
			JsonRequestBehavior.AllowGet);
		}

		public async Task<JsonCamelCaseResult> GetEditData(string id)
		{
			var data = await DbContext.NewsListInfo.AsNoTracking().FirstOrDefaultAsync(x => x.ID == id);
			if (data != null)
			{
				var result = new
				{
					NewsListName = data.NewsListName,
					NewsListPic = Path.GetFileName(data.NewsListPic),
					NewsListPosition = data.NewsListPosition,
					NewsStyle = data.NewsStyle,
					Link = data.Link,
					BackgroundColor = !string.IsNullOrEmpty(data.BackgroundColor) ? data.BackgroundColor : "#ffffff",
					BackgroundOpacity = data.BackgroundOpacity.HasValue ? data.BackgroundOpacity : 1,
					FontSize = !string.IsNullOrEmpty(data.FontSize) ? data.FontSize : "16px",
					FontWeight = !string.IsNullOrEmpty(data.FontWeight) ? data.FontWeight : "normal",
					FontStyle = !string.IsNullOrEmpty(data.FontStyle) ? data.FontStyle : "normal",
					FontColor = !string.IsNullOrEmpty(data.FontColor) ? data.FontColor : "#c30d23",
					LineColor = !string.IsNullOrEmpty(data.LineColor) ? data.LineColor : "#c30d23",
					IsShowMore = data.IsShowMore,
					MoreColor = !string.IsNullOrEmpty(data.MoreColor) ? data.MoreColor : "#8f8f8f",
					Sort = data.Sort,
					Status = data.Status,
					Remark = data.Remark
				};
				return JsonCamelCase(Utility.CreateSuccessJsonResult(string.Empty, result),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("Create/{ConferenceId}")]
		public async Task<JsonResult> Create(ConferenceNewsListModel model, FormCollection formCollection)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var result = await DbContext.NewsListInfo.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ConferenceId == model.ConferenceId &&
						x.NewsListName == model.NewsListName);

			if (result != null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(
						string.Format(Resources.MsgRecordExist, Resources.Name)),
						JsonRequestBehavior.AllowGet);
			}

			if (model.NewsListPic != null)
			{
				string nickName = DbContext.ConferenceMaster.AsNoTracking().FirstOrDefault(x => x.ID == model.ConferenceId)?.ConferenceNickName;
				string folder = Path.Combine(ConstValues.ConferenceImg, nickName);
				string pfolder = Path.Combine(Server.MapPath(ConstValues.ConferenceImg), nickName);

				string fileName = nickName + ConstValues.strHyphen +
						Path.GetExtension(model.NewsListPic.FileName).Replace(".", "").ToUpper() + ConstValues.strHyphen +
						DateTime.Now.ToString("yyyy") + ConstValues.strHyphen +
						Utility.GetRandom() + Path.GetExtension(model.NewsListPic.FileName);
				model.NewsListPicPath = Path.Combine(folder, fileName);
				var saveFileTask = Task.Run(() =>
				{
					string pFullPath = Path.Combine(pfolder, fileName);
					if (!Directory.Exists(pfolder))
					{
						Directory.CreateDirectory(pfolder);
					}
					model.NewsListPic.SaveAs(pFullPath);
				});
				Task.WaitAll(saveFileTask);
			}

			var newId = Utility.GetTableId(ConstValues.TableName.NewsListInfo);

			var newsListInfo = new NewsListInfo
			{
				ID = newId,
				NewsListName = model.NewsListName?.Trim(),
				NewsListPic = model.NewsListPicPath?.Trim(),
				NewsListPosition = model.NewsListPosition?.Trim(),
				NewsStyle = model.NewsStyle?.Trim(),
				Link = !string.IsNullOrWhiteSpace(model.Link) ? model.Link.Trim() :
						ConstValues.SystemWeb + "/MeetingNewsList/Index/" + newId,

				BackgroundColor = model.BackgroundColor,
				BackgroundOpacity = model.BackgroundOpacity,
				FontSize = model.FontSize,
				FontWeight = model.FontWeight,
				FontStyle = model.FontStyle,
				FontColor = model.FontColor,
				LineColor = model.LineColor,
				IsShowMore = formCollection.AllKeys.FirstOrDefault(x => x == "IsShowMore") == null ? false : true,
				MoreColor = model.MoreColor,

				ConferenceId = model.ConferenceId,
				Status = model.Status,
				Sort = model.Sort.HasValue ? model.Sort.Value : ConstValues.DefaultSort,
				Remark = model.Remark?.Trim(),
				Creator = LoginUser.UserName,
				CreateIP = LoginUser.IP,
				CreateDate = DateTime.Now
			};
			DbContext.NewsListInfo.Add(newsListInfo);
			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
					JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("Modify/{ConferenceId}")]
		public async Task<JsonResult> Modify(ConferenceNewsListModel model, FormCollection formCollection)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var exist = await DbContext.NewsListInfo.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ID != model.Id &&
						x.ConferenceId == model.ConferenceId &&
						x.NewsListName == model.NewsListName);

			if (exist != null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(
						string.Format(Resources.MsgRecordExist, Resources.NewsListName)),
						JsonRequestBehavior.AllowGet);
			}

			var result = await DbContext.NewsListInfo.FirstOrDefaultAsync(x => x.ID == model.Id);

			if (result == null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}

			if (model.NewsListPic != null)
			{
				string nickName = DbContext.ConferenceMaster.AsNoTracking().FirstOrDefault(x => x.ID == model.ConferenceId)?.ConferenceNickName;
				string folder = Path.Combine(ConstValues.ConferenceImg, nickName);
				string pfolder = Path.Combine(Server.MapPath(ConstValues.ConferenceImg), nickName);

				string fileName = nickName + ConstValues.strHyphen +
						Path.GetExtension(model.NewsListPic.FileName).Replace(".", "").ToUpper() + ConstValues.strHyphen +
						DateTime.Now.ToString("yyyy") + ConstValues.strHyphen +
						Utility.GetRandom() + Path.GetExtension(model.NewsListPic.FileName);
				model.NewsListPicPath = Path.Combine(folder, fileName);
				var saveFileTask = Task.Run(() =>
				{
					string pFullPath = Path.Combine(pfolder, fileName);
					if (!Directory.Exists(pfolder))
					{
						Directory.CreateDirectory(pfolder);
					}
					model.NewsListPic.SaveAs(pFullPath);
				});
				Task.WaitAll(saveFileTask);
				result.NewsListPic = model.NewsListPicPath?.Trim();
			}
			else if (string.IsNullOrEmpty(model.NewsListPicPath))
			{
				result.NewsListPic = string.Empty;
			}

			result.NewsListName = model.NewsListName?.Trim();
			result.NewsListPosition = model.NewsListPosition?.Trim();
			result.NewsStyle = model.NewsStyle?.Trim();
			result.Link = !string.IsNullOrWhiteSpace(model.Link) ? model.Link.Trim() :
					ConstValues.SystemWeb + "/MeetingNewsList/Index/" + result.ID;

			result.BackgroundColor = model.BackgroundColor;
			result.BackgroundOpacity = model.BackgroundOpacity;
			result.FontSize = model.FontSize;
			result.FontWeight = model.FontWeight;
			result.FontStyle = model.FontStyle;
			result.FontColor = model.FontColor;
			result.LineColor = model.LineColor;
			result.IsShowMore = formCollection.AllKeys.FirstOrDefault(x => x == "IsShowMore") == null ? false : true;
			result.MoreColor = model.MoreColor;

			result.Sort = model.Sort.HasValue ? model.Sort.Value : ConstValues.DefaultSort;
			result.Remark = model.Remark?.Trim();
			result.Status = model.Status;
			result.Updater = LoginUser.UserName;
			result.UpdateDate = DateTime.Now;
			result.UpdateIP = LoginUser.IP;

			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
					JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("Delete/{ConferenceId}")]
		public async Task<JsonResult> Delete(ConferenceNewsListModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var exist = await DbContext.NewsInfo.AsNoTracking()
					.Where(x => x.NewsListId == model.Id).ToListAsync();

			if (exist.Count > 0)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgUsingCanNotDelete),
						JsonRequestBehavior.AllowGet);
			}

			var result = await DbContext.NewsListInfo.FirstOrDefaultAsync(x => x.ID == model.Id);

			if (result != null)
			{
				DbContext.NewsListInfo.Remove(result);
				await DbContext.SaveChangesAsync();

				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessDelete),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[Route("ShowPic/{id}")]
		public async Task<ActionResult> ShowPic(string id)
		{
			var tran = await DbContext.NewsListInfo.AsNoTracking().FirstOrDefaultAsync(x => x.ID == id);

			if (tran != null && !string.IsNullOrEmpty(tran.NewsListPic))
			{
				return File(tran.NewsListPic, Application.Octet, Path.GetFileName(tran.NewsListPic));
			}
			else
			{
				return File("~/Images/ConferenceNoPic.png", Application.Octet, Path.GetFileName("~/Images/ConferenceNoPic.png"));
			}
		}
	}
}